package com.itheima.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.pojo.CheckItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;

/**
 * 地址服务
 */
@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;
    @Autowired
    private JedisPool jedisPool;

    //新增地址
    public void add(Address address) {
        addressDao.add(address);
        //新增地址时将图片名称保存在Redis
        jedisPool.getResource().sadd(RedisConstant.ADDRESS_PIC_DB_RESOURCES,address.getImg());
    }

    //删除地址，先判断中间表中是否有数据
    public void delete(Integer id) {
        long count = addressDao.selectCountByAddressId(id);
        if(count > 0){
            //已经被关联，不能删除
            throw new RuntimeException(MessageConstant.DELETE_ADDRESS_FAIL);
        }else{
            //可以删除
            addressDao.deleteById(id);
        }

    }

    //分页
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage,pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面
        Page<Address> page = addressDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //回显数据
    public Address findById(Integer id) {
        return addressDao.findById(id);
    }

    //编辑
    public void edit(Address address) {
        addressDao.edit(address);
    }

    //查询所有地址，在预约时使用
    public List<Address> findAll() {
        return addressDao.findAll();
    }

}
